import { _decorator, Component, Node, Label, UIOpacity, UITransform } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PopupBox')
export class PopupBox extends Component {

    @property(Label)
    title: Label = null

    @property(UITransform)
    bg: UITransform = null

    @property(UIOpacity)
    opacityComp: UIOpacity = null

    start() {
        this.node.active = false
    }

    update(deltaTime: number) {

    }

    popUp(title: string, delay?: number) {
        this.title.string = title
        const chw = this.countChineseCharacters(title)
        this.bg.width = chw * 20 + (title.length - chw) * 10 + 100
        this.opacityComp.opacity = 255
        this.node.active = true
        if (delay == undefined) {
            delay = 800
        }
        setTimeout(() => {
            const remove = setInterval(() => {
                if (this.opacityComp.opacity > 0) {
                    this.opacityComp.opacity -= 10
                } else {
                    this.opacityComp.opacity = 0
                    clearInterval(remove)
                }
            }, 1)
        }, delay)
    }

    countChineseCharacters(str: string): number {
        const pattern = /[\u4e00-\u9fa5]/g; // 匹配中文字符的正则表达式
        const matches = str.match(pattern); // 使用正则表达式匹配中文字符
        return matches ? matches.length : 0; // 返回匹配到的中文字符个数
    }
}

